/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package main.genomemap;

import javautil.collections.ArrayUtil;
import javautil.collections.RaggedArrayException;
import javautil.collections.SetUtil;
import javautil.io.IOUtil;
import javautil.io.LogUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author stewari1
 */
public class ReadLegacyFiles {

    public static void main(String[] args) {


//      File hybridFile = new File("C:/Documents and Settings/stewari1/Desktop/hybrid_7.txt");
//      File cloneNamesFile = new File("C:/Documents and Settings/stewari1/Desktop/clone_names_7.txt");
//      File outputFile = new File("C:/Documents and Settings/stewari1/Desktop/hybrid_7_out.txt");
//      fromManagedToLegacyHybridData(hybridFile, cloneNamesFile, outputFile);
//       File inputFile = new File("C:/Documents and Settings/stewari1/Desktop/cosmid7.dat.new");
//       File outputFile = new File("C:/Documents and Settings/stewari1/Desktop/cosmid7_out.dat.new");
//       fromLegacyToManagedHybridData(inputFile, outputFile);
        getAllLegacyOrders();
    }

    /**
     * Method description
     */
    private static void getAllLegacyOrders() {

        for (int i = 0; i < 7; i++) {

            String refFilePath = "resources/dataCollection/probe_names_" + (i + 1) + ".txt";
            String legFilePath =
                "resources/dataCollection/final_probe_order_names/final_probe_order_names_"
                + (i + 1) + ".txt";

            LogUtil.print(getLegacyProbeOrder(new File(refFilePath), new File(legFilePath)));
        }
    }

    /**
     * Method description
     *
     * @param referenceFile description
     * @param legacyFile description
     *
     * @return description
     */
    private static int[] getLegacyProbeOrder(File referenceFile, File legacyFile) {

        int[] embedFrom   = null;
        String[] refNames = null;

        try {


            // get all te names (delimited by new line) from the reference file
            refNames = IOUtil.readFileContentToString(referenceFile).split("\n");

            String[] legacyNames = IOUtil.readFileContentToString(legacyFile).split("\n");

            embedFrom = new int[legacyNames.length];

            for (int i = 0; i < legacyNames.length; i++) {

                boolean found = false;

                for (int j = 0; j < refNames.length; j++) {

                    if (legacyNames[i].equals(refNames[j])) {

                        found        = true;
                        embedFrom[i] = j;
                    }
                }

                if (!found) {
                    System.out.println("Legacy Name: " + legacyNames[i] + "isn`t found");
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ReadLegacyFiles.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ReadLegacyFiles.class.getName()).log(Level.SEVERE, null, ex);
        }

        int[] embedTo = ArrayUtil.IntegerSequence(refNames.length, false);

        return SetUtil.getSubSeq(embedTo, embedFrom);
    }

    /**
     * reads hybrid data from the following format.
     * <p> input format
     * 168   1746   1
     * X107C02   0000010000001
     * X107E04   000000100000
     * <p> output format
     * 0,0,0,0,0,1,0,0,0,0,0,0,1
     * 0,0,0,0,0,1,0,0,0,0,0,0,0
     * @param inputFile
     * @param outputFile
     */
    public static void fromLegacyToManagedHybridData(File inputFile, File outputFile) {

        BufferedReader buffReader = null;
        String line               = null;
        ArrayList<String> strData = new ArrayList<>();
        StringBuilder outputStr   = new StringBuilder(400000);

        try {

            buffReader = new BufferedReader(new FileReader(inputFile));
            line       = buffReader.readLine();    // ignore the first line
            line       = buffReader.readLine();

            while (line != null) {

                String[] parts = line.split(" ");

                strData.add(parts[parts.length - 1]);    // take the last one

                line = buffReader.readLine();
            }

            for (String str : strData) {

                for (int i = 0; i < str.length() - 1; i++) {

                    outputStr.append(str.charAt(i) + ",");
                }

                outputStr.append(str.charAt(str.length() - 1) + "\n");
            }

            IOUtil.writeToFile(outputFile, outputStr.toString());

        } catch (FileNotFoundException ex) {
            Logger.getLogger(ReadLegacyFiles.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ReadLegacyFiles.class.getName()).log(Level.SEVERE, null, ex);
        } finally {

            try {
                buffReader.close();
            } catch (IOException ex) {
                Logger.getLogger(ReadLegacyFiles.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void fromManagedToLegacyHybridData(File hybridFile, File cloneNamesFile,
            File outputFile) {

        try {

            int[][] hybridData = ArrayUtil.get2DIntMArray(hybridFile, false, ",");
            int probeCount     = hybridData[0].length;
            int cloneCount     = hybridData.length;


            // verify cloner numbers
            String[] cloneNames = IOUtil.readFileContentToString(cloneNamesFile).split("\r\n");

            if (cloneNames.length != cloneCount) {

                System.out.println("clone # from hybrid data: " + cloneCount + "\n"
                                   + "clone # from clone names file: " + cloneNames.length);
            }

            StringBuilder outputStr = new StringBuilder(400000);

            outputStr.append(probeCount + "   " + cloneCount + "   " + 1 + "\n");

            for (int cloneIndex = 0; cloneIndex < cloneCount; cloneIndex++) {

                outputStr.append(cloneNames[cloneIndex] + "   ");

                for (int probeIndex = 0; probeIndex < probeCount; probeIndex++) {

                    outputStr.append(hybridData[cloneIndex][probeIndex]);
                }

                outputStr.append("\n");
            }

            IOUtil.writeToFile(outputFile, outputStr.toString());

        } catch (FileNotFoundException ex) {
            Logger.getLogger(ReadLegacyFiles.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RaggedArrayException ex) {
            Logger.getLogger(ReadLegacyFiles.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | NumberFormatException ex) {
            Logger.getLogger(ReadLegacyFiles.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
